package com.elite.controller;

import com.alibaba.fastjson.JSON;
import com.elite.entity.File;
import com.elite.entity.FileGoods;
import com.elite.service.FileGoodsService;
import com.elite.service.FileService;
import com.elite.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;

/**
 * Created by Administrator on 2017/1/22.
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    FileService fileService;
    @Autowired
    UserService userService;
    @Autowired
    FileGoodsService fileGoodsService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpSession session;


    private static final Logger LOGGER = Logger.getLogger(String.valueOf(FileController.class));

    /**
     *2、添加头像，或者更新头像
     * @param fileName
     * @param fileUrl
     * @param fileSize
     * @param fileType
     * @param userId
     */
    public void addFileImg(String fileName,String fileUrl,Integer fileSize,String fileType,Integer userId){
        File file = new File();
        Integer fileId1 = null;
        try{
             fileId1 = fileService.selectByUserId(userId).getFileId();
        }catch (NullPointerException e){
            e.printStackTrace();
        }
        if (fileId1 != null){
            File file3 = fileService.selectByPrimaryKey(fileId1);
            file3.setFileName(fileName);
            file3.setFileUrl(fileUrl);
            file3.setFileSize(fileSize);
            file3.setFileType(fileType);
            fileService.updateByPrimaryKey(file3);
        }else {
            if (userService.selectById(userId)!=null){
                file.setFileName(fileName);
                file.setFileUrl(fileUrl);
                file.setFileSize(fileSize);
                file.setFileType(fileType);
                fileService.addFileImg(file);
            }
        }
        addFileGoods(userId,fileName);
    }

    /**
     * 3、通过图片名字唯一性确定该头像属于哪个用户
     * @param userId
     * @param fileName
     */
    public void addFileGoods(Integer userId,String fileName){
        FileGoods fileGoods2= fileService.selectByUserId(userId);
        File file1 = fileService.selectByFileName(fileName);
        if (fileGoods2!=null){

        }else {
            FileGoods fileGoods = new FileGoods();
            if (file1!=null){
                fileGoods.setFileId(file1.getFileId());
                fileGoods.setGoodsId(null);
                fileGoods.setUserId(userId);
                fileService.addFileGoods(fileGoods);
            }
        }
    }

    /**
     *4、从数据库取出图片传给前端显示
     * @param userId
     * @return
     */
    @RequestMapping(value = "/selectImg",method = RequestMethod.POST)
    public String selectImg(Integer userId){
        FileGoods fileGoods1 = fileService.selectByUserId(userId);
        String result;
        if (fileGoods1!=null){
            Integer fileId = fileGoods1.getFileId();
            File file2 = fileService.selectByPrimaryKey(fileId);
            if (file2!=null){
                return JSON.toJSON(file2).toString();
            }else {
                result = "false";
                return JSON.toJSON(result).toString();
            }
        }else {
            result = "none";
            return JSON.toJSON(result).toString();
        }
    }


    /**
     *5、通过商品id查询多个图片id
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/selectByGoodsId",method = RequestMethod.GET)
    public String selectByGoodsId(Integer goodsId){
        LOGGER.info("??????????????????????????????????????????"+goodsId);
        List<FileGoods> fileGoods2 = fileGoodsService.selectAllByGoodsId(goodsId);
        Iterator it = fileGoods2.iterator();
        while (it.hasNext()){

            LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+String.valueOf(it.next()));
        }

        return JSON.toJSON(fileGoods2).toString();
    }


    /**
     *6、通过file id查询多个图片
     * @param fileId
     * @return
     */
    @RequestMapping(value = "/selectByFileId",method = RequestMethod.GET)
    public String selectByFileId(Integer fileId){
        File file = fileService.selectByPrimaryKey(fileId);
        return JSON.toJSON(file).toString();
    }
    /**
     * 卖家上传多张商品图片
     * @param fileName
     * @param fileUrl
     * @param fileSize
     * @param fileType
     * @param goodsId
     */
    public void addFilesImg(String fileName,String fileUrl,Integer fileSize,String fileType,Integer goodsId){

        File file4 = new File();
        if (goodsId != null){

            file4.setFileName(fileName);
            file4.setFileUrl(fileUrl);
            file4.setFileSize(fileSize);
            file4.setFileType(fileType);
            fileService.addFileImg(file4);
        }
        addFilesGoods(goodsId, fileName);
    }

    /**
     *
     * @param goodsId
     * @param fileName
     */
    public void addFilesGoods(Integer goodsId,String fileName){

        FileGoods fileGoods3 = new FileGoods();
        File file5 = fileService.selectByFileName(fileName);

        if (file5 != null){
            fileGoods3.setFileId(file5.getFileId());
            fileGoods3.setGoodsId(goodsId);
            fileGoods3.setUserId(null);
            fileService.addFileGoods(fileGoods3);
        }

    }

    /**
     * 1、同过form表单获取这个图片，并把这个写入指定文件夹。同时将相应的参数传给addFileImg
     * @param file1
     */
    @RequestMapping(value = "/test",method = RequestMethod.POST)
    public void uploadToLocal(@RequestParam("file") MultipartFile[] file1) throws MalformedURLException {
/*
        String savePath = "C:\\Users\\hbl\\Desktop\\dev\\new sctu\\Fengwei\\src\\main\\webapp\\resources\\images";
*/
        String savePath = "C:\\Program Files (x86)\\Apache Software Foundation\\Tomcat 9.0\\webapps\\fengwei\\resources\\images";
        //userId
        Integer userId = null;
        Integer goodsId = null;
        if (file1.length>1){
            goodsId = Integer.parseInt(request.getParameter("goodsId"));
            LOGGER.info("-------------------->>>>>>>>>>"+goodsId);
        } else {
            userId = Integer.parseInt(request.getParameter("userId"));
        }

        String newFileName = null;
        String filePath = null;
        int size = 0;
        String suffixName = null;
        for (MultipartFile file:file1){
            if(file!=null && !file.isEmpty()){
                //获取文件名称
                String fileName=file.getOriginalFilename();
                //获取后缀名
                suffixName=fileName.substring(fileName.indexOf(".") + 1);
                //图片大小
                size = (int) file.getSize();
                //新文件名称
                newFileName=System.currentTimeMillis()+"."+suffixName;
                //新文件路劲
                filePath=savePath+"\\"+newFileName;
                //获取存储文件路径
                java.io.File fileDir=new java.io.File(savePath);
                if(!fileDir.exists()){
                    //如果文件夹没有：新建
                    fileDir.mkdirs();
                }
                FileOutputStream fos=null;
                try {
                    fos=new FileOutputStream(filePath);
                    fos.write(file.getBytes());
                    fos.flush();
                } catch (Exception e) {
                    e.printStackTrace();

                } finally{
                    try {
                        if(fos!=null){
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();

                    }
                }
            }

            if (file1.length > 1){
                LOGGER.info("-------------------->>>>>>>>>>>>>>>>" + file1.length);
                addFilesImg(newFileName, filePath, size, suffixName, goodsId);
            }else {
                addFileImg(newFileName, filePath, size, suffixName, userId);
            }

        }

    }
}




